# 
# configuration.rb
# 
# Created on 12/09/2007, 16:33:34
#

# BREADCRUBS: Controller class methods for getting information on controller chain
#             This methods should be inserted on ActionController::Base
module AutoRest
  module BreadcrumbsClassMethods
    
    # Store controller relationships for nested resources
    def ar_controller_parents
      @@controller_parents||= {}
    end
    
    # Is the controller on the controller chain?
    def ar_has_controller_on_chain? kontroller
      ar_controller_parents.has_key? kontroller.controller_class_name.intern
    end
    
    # As a single resource may have many parents, look in the request params 
    # to see wich one is selected.
    def ar_select_parent controller_parents, request_params
      return nil if !controller_parents || controller_parents.empty?
      first= controller_parents.to_a.first
      return first if controller_parents.size == 1
      
      controller_parents.each do |cont|
        res_id= "#{cont.to_s.constantize.ardata.resource.singular}_id"
        return cont if request_params.include? res_id
      end
      
      return first 
    end
    
    # Yields the controllers in chain from the root to the last child
    def ar_controller_chain current_controller, request_params
      
      chain= []
      
      # Following if is for allowing Controller and also Controller.new as params
      first_controller= Class === current_controller.class ? current_controller : current_controller.class
      
      current_controller_key= first_controller.controller_class_name.intern
      
      return chain if not ar_controller_parents.include?(current_controller_key)

      # Use the first controller as first key
      chain << current_controller_key
      
      next_controller= ar_select_parent(ar_controller_parents[current_controller_key], request_params)
        
      while next_controller
        if chain.include? next_controller # I'm not very fond of infinit loops :)
          break
        else
          chain << next_controller
          current_controller_key= next_controller
          next_controller= ar_select_parent(ar_controller_parents[current_controller_key], request_params)
        end
      end
      
      # Convert the symbols into Objects.
      chain.map! {|e| e.to_s.constantize }
      
      return chain if !block_given?
      
      chain.reverse_each do |controller|
        yield controller
      end
    end
    
  end
end

ActionController::Base.extend AutoRest::BreadcrumbsClassMethods